package com.autumn.xa.a.tuling.jvm;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;

public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        // 实现了双亲委派，不需要修改，直接调用父类的
        return super.loadClass(name);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        byte[] data = getData(name);

        Class<?> aClass = defineClass(name, data, 0, data.length);

        return aClass;
    }

    byte[] getData(String name) {
        try {
            name = name.replaceAll("\\.","/");
            FileInputStream in = new FileInputStream(classPath + "/" + name);
            int len = in.available();
            byte[] data1 = new byte[len];
            in.read();
            in.close();
            return data1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        MyClassLoader classLoader = new MyClassLoader("D:\\temp");

        Class clazz = classLoader.loadClass("com.autumn.xa.a.tuling.jvm.JAVAPClass");
        Object obj = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("compute", null);
        Object result = method.invoke(obj, null);
        System.out.println(clazz.getClassLoader().getClass().getName());
        System.out.println(result.toString());
    }
}
